package com.yu.crm.jobs;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.whyxzz.netreplyutil.NetReplyUtil;
import com.yu.crm.domain.pojo.CallerReservationPeople;
import com.yu.crm.domain.pojo.CrmEarlyWarningDiscernArea;
import com.yu.crm.service.impl.AttendanceInfoService;
import com.yu.crm.service.impl.CallerReservationPeopleService;
import com.yu.crm.service.impl.CrmEarlyWarningDiscernAreaService;
import com.yu.crm.utils.DateUtil;
import com.yu.crm.utils.FileUtil;
import com.yu.crm.utils.OnLineNotify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.InetAddress;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;



/**
 * 定时任务类 需要在启动类增加@EnableScheduling注解
 *
 * @author Lee
 */
@Component
@EnableScheduling
@Slf4j
public class ScheduledTasks {

    @Autowired
    AttendanceInfoService attendanceInfoService;

    @Autowired
    CallerReservationPeopleService callerReservationPeopleService;

    @Autowired
    CrmEarlyWarningDiscernAreaService discernAreaService;

    /**
     * 每天晚上十一点半定时查询根据当前时间判断是否需要记录考勤，并设置缺勤记录
     */
    @Scheduled(cron = "${wechat.cronSales}")
    public void listByTimeMessage() {
        log.info("=======根据当前时间判断是否需要记录考勤，并设置缺勤记录开始==============");
        attendanceInfoService.addStatusFive();
        log.info("=======根据当前时间判断是否需要记录考勤，并设置缺勤记录结束==============");
    }

    /**
     * 每天晚上一点将前一天的访客记录导入
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void CopyCaller() {
        log.info("=======前一天预约用户表导入 开始==============");
        List<CallerReservationPeople> list = selectAll();
        if (list!=null&&list.size()>0){
            callerReservationPeopleService.saveBatch(list);
        }
        log.info("=======前一天预约用户表导入结束==============");
    }

    @Value("${img_path}")
    private static final String img_path = "/";
    /**
     * 每晚2点将超过保存期限的照片删除
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void deleteFile() {
        QueryWrapper<CrmEarlyWarningDiscernArea> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted",0);
        wrapper.isNotNull("camera_id");
        List<CrmEarlyWarningDiscernArea> list = discernAreaService.list(wrapper);
        for (CrmEarlyWarningDiscernArea discernArea : list) {
            //根据修改时间判断               修改时间+保存时间 = 当前时间       删除修改时间以前的数据
            FileUtil.moveFileToReady(img_path + "discern-area", Integer.valueOf(discernArea.getSaveTime()));
        }
    }





    @PostConstruct
    public void onLineNotify() {
        System.out.println("====Hello World!====");
        OnLineNotify onLineNotify = new OnLineNotify();
        try {
            InetAddress ia = null;
            //获取本机ip地址
            ia = ia.getLocalHost();
            //NetReplyUtil.init("192.168.10.97", 60000, onLineNotify);
            NetReplyUtil.init(ia.getHostAddress(), 60000, onLineNotify);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询昨天新增的访客名单
     * @return
     */
    private List<CallerReservationPeople> selectAll() {

        List<CallerReservationPeople> list = new ArrayList<>();
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection("jdbc:mysql://47.111.184.95:3306/yxzz_caller_zxt?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8", "root", "mysql_xx@2019");

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * FROM caller_reservation_people  where DATEDIFF(gmt_create,NOW())=-1";
            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库
            while (rs.next()) {
                // 通过字段检索
                CallerReservationPeople pojo = new CallerReservationPeople();

                pojo.setId(rs.getLong("id"));
                pojo.setWxId(rs.getString("wx_id"));
                pojo.setEmployeeId(rs.getLong("employee_id"));
                pojo.setPhone(rs.getString("phone"));
                pojo.setOpenId(rs.getString("open_id"));
                pojo.setNickName(rs.getString("nick_name"));
                pojo.setWxName(rs.getString("wx_name"));
                pojo.setSex(rs.getInt("sex"));
                pojo.setIdentity(rs.getString("identity"));
                pojo.setUnitName(rs.getString("unit_name"));
                pojo.setDepartmentName(rs.getString("department_name"));
                pojo.setLicensePlateNumber(rs.getString("license_plate_number"));
                pojo.setHeadimgUrl(rs.getString("headimg_url"));
                pojo.setCertificateUrl(rs.getString("certificate_url"));
                pojo.setCertificateEigen(rs.getBytes("certificate_eigen"));
                pojo.setIdCardFeature(rs.getBytes("id_card_feature"));
                pojo.setRemindTime(rs.getInt("remind_time"));
                pojo.setIsRemind(rs.getInt("is_remind"));
                pojo.setPhotoShow(rs.getString("photo_show"));
                pojo.setVideoShow(rs.getString("video_show"));
                pojo.setHomeUrl(rs.getString("home_url"));
                pojo.setShare(rs.getString("share"));
                pojo.setGmtCreate(DateUtil.date2LocalDateTime(rs.getTimestamp("gmt_create")));
                pojo.setGmtModified(DateUtil.date2LocalDateTime(rs.getTimestamp("gmt_modified")));
                pojo.setIsDeleted(rs.getInt("is_deleted"));

                list.add(pojo);
            }
            // 完成后关闭
            rs.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se2) {
                se2.printStackTrace();
            }
            try {
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }

        return list;
    }


}
